package com.netsdk.lht2.handle;

import com.netsdk.demo.util.sql.EventDto;
import com.netsdk.demo.util.sql.JdbcUtils;
import com.sun.jna.Pointer;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public abstract class EventHandle {

    protected static final File picturePath;
    protected final static ConcurrentHashMap<Integer,String> channelMapping = new ConcurrentHashMap<>();

    static {
        picturePath = new File("C:\\juyuan\\devtoos\\apache-tomcat-8.5.65\\webapps\\qxjtImg");
        if (!picturePath.exists()) {
            picturePath.mkdirs();
        }
        // 胜辛路-陈家山路-北侧2-南HG  已经使用过的：377，383，391，401,410
        channelMapping.put(417,"352");
        // 陈家山路-胜辛路-东侧-西HG 已经使用过的：359，388，392，407
        channelMapping.put(414,"330");
        // 胜辛路-陈家山路-南侧2-北HG 已经使用过的：396,408
        channelMapping.put(415,"323");
        // 陈家山路-胜辛路-西侧-东HG 已经使用过的：398，402,409
        channelMapping.put(416,"324");
        // 平城路-城北路-东侧-西HG 已经使用过的：367，390，400,411
        channelMapping.put(418,"367");
        // 城北路-平成路-南侧-北HG 已经使用过的：368,379，382,406
        channelMapping.put(419,"368");
        // 平城路-城北路-西侧-东HG 已经使用过的：369,380，386，387,412
        channelMapping.put(420,"369");
        // 城北路-平成路-北侧-南 已经使用过的：394,413
        channelMapping.put(421,"329");

        updateChannel();
    }

    // 同步 channel 号
    private static void updateChannel() {
        String updateSQLTemplate = "update jyxq_qxjt_event set channel='%s' where channel='%s';";
        for (Map.Entry<Integer, String> entry : channelMapping.entrySet()) {
            Integer key = entry.getKey();
            String value = entry.getValue();
            if (!key.toString().equals(value)){
                String sql = String.format(updateSQLTemplate, value, key);
                JdbcUtils.update(sql);
            }
        }
    }

    /**
     * 获取 channelId 映射
     * @param nChannelID 通道id
     * @return 映射后的通道id
     */
    protected String getChannelMapping(int nChannelID){
        String mapping = channelMapping.get(nChannelID);
        if(mapping == null){
            System.out.println("无法找到Channel映射，请配置,"+ nChannelID);
            mapping = nChannelID + "";
        }
        return mapping;
    }

   public abstract  void handle(int dwAlarmType, Pointer pAlarmInfo, Pointer pBuffer, int dwBufSize,
                Pointer dwUser, int nSequence, Pointer reserved) throws UnsupportedEncodingException;


    /*
    * 插入事件到数据库
    * */
    protected void insertEventDto(EventDto dto){
         JdbcUtils.insert(dto);
    }
}
